package main

import (
	"flag"
	"fmt"
	"io"
	"net"
	"os"
)

type Client struct {
	ServerIp   string
	ServerPort int
	Name       string
	con        net.Conn
	flag       int //当前client的l聊天模式
}

func NewClient(ServerIp string, ServerPort int) *Client {
	//创建客户端对象
	client := &Client{
		ServerIp:   ServerIp,
		ServerPort: ServerPort,
		flag:       999,
	}
	//链接server
	conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", ServerIp, ServerPort))
	if err != nil {
		fmt.Println("dail error ", err)
		return nil
	}
	client.con = conn
	//返回对象
	return client
}

var serverIp string
var serverPort int

//init 在 main 函数之前执行
//./client -ip 127.0.0.1 -port 8888
func init() {
	//类似于启动时命令行指令解析  ip -ip   默认值 对值的说明
	flag.StringVar(&serverIp, "ip", "127.0.0.1", "设置服务器IP地址(默认是127.0.0.1)")
	flag.IntVar(&serverPort, "port", 8888, "设置服务器端口(默认是8888)")
}

//客户端菜单模式
func (client *Client) menu() bool {
	var flag int
	fmt.Println("1.[公聊模式]")
	fmt.Println("2.[私聊模式]")
	fmt.Println("3.[更新用户名]")
	fmt.Println("0.[退出]")
	fmt.Scan(&flag)
	if flag >= 0 && flag <= 3 {
		client.flag = flag
		return true
	} else {
		fmt.Println(">>>>请输入合法范围内的数字<<<<")
		return false
	}
}

//客户端业务模式
func (client *Client) Run() {
	//等于 0 直接退出
	for client.flag != 0 {
		for client.menu() != true {
		}
		//根据不同的模式处理不同的业务
		switch client.flag {
		case 1:
			client.PublicChat()
			break
		case 2:
			client.PrivateChat()
			break
		case 3:
			client.UpdateName()
			break
		}
	}
}

//修改名字
func (client *Client) UpdateName() bool {
	fmt.Println(">>>>>请输入新名字：")
	fmt.Scan(&client.Name)
	sendMag := "rename|" + client.Name
	_, err := client.con.Write([]byte(sendMag))
	if err != nil {
		fmt.Println("conn.Write err:", err)
		return false
	}
	return true
}

//公聊模式
func (client *Client) PublicChat() {
	//提示用户输入消息
	var chatMsg string
	fmt.Println(">>>>请输入群聊模式聊天内容")
	fmt.Scan(&chatMsg)
	for chatMsg != "exit" {
		//消息不为空则发送
		if len(chatMsg) != 0 {
			//发给服务器
			_, err := client.con.Write([]byte(chatMsg))
			if err != nil {
				fmt.Println("conn Write err:", err)
				break
			}
		}
		chatMsg = ""
		fmt.Println(">>>>请输入聊天内容，exit退出.")
		fmt.Scan(&chatMsg)
	}
}

//私聊模式
func (client *Client) PrivateChat() {
	var remoteName string
	var remoteContent string

	client.SelectUsers()
	fmt.Println(">>>请输入要对话的名字：exit 退出")
	fmt.Scan(&remoteName)

	for remoteName != "exit" {
		fmt.Println(">>>>请输入消息内容, exit退出:")
		fmt.Scan(&remoteContent)

		for remoteContent != "exit" {
			//消息不为空则发送
			if len(remoteContent) > 0 {
				sendMsg := "to|" + remoteName + "|" + remoteContent
				_, err := client.con.Write([]byte(sendMsg))
				if err != nil {
					fmt.Println("conn Write err:", err)
					break
				}
			}
			remoteContent = ""
			fmt.Println(">>>>请输入消息内容, exit退出:")
			fmt.Scan(&remoteContent)
		}
		//换人聊天
		client.SelectUsers()
		fmt.Println(">>>>请输入聊天对象[用户名], exit退出:")
		fmt.Scan(&remoteName)
	}
}

//查询在线用户
func (client *Client) SelectUsers() {
	sendMag := "who"
	//那么当服务器返回时 直接打在了公屏上
	_, err := client.con.Write([]byte(sendMag))
	if err != nil {
		fmt.Println("conn Write err:", err)
		return
	}
}

//读写分离
//单独处理server回应的消息，直接显示到标准输出即可
func (client *Client) DealResponse() {
	//一旦client.conn有数据，就直接copy到stdout标准输出上, 永久阻塞监听
	io.Copy(os.Stdout, client.con)
	//不断阻塞的从流中获取数据
	//for true {
	//	buf := make([]byte, 1045)
	//	client.con.Read(buf)
	//	fmt.Println(buf)
	//}
}

func main() {
	//命令行解析
	flag.Parse()

	client := NewClient(serverIp, serverPort)
	if client == nil {
		fmt.Println(">>>>> 链接服务器失败...")
		return
	}
	fmt.Println(">>>>> 链接服务器成功...")
	//单独开启一个goroutine去处理server的回执消息
	go client.DealResponse()
	//启动客户端的业务
	client.Run()
}
